package com.whh.downloader;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

import org.apache.log4j.Logger;

public class ImgDownloader {
	private static final Logger logger = Logger.getLogger(ImgDownloader.class);

	
	public static void main(String[] args) {
	
	}

	/**
	 * 下载图片
	 * @param imgUrl
	 * @param fileURL
	 */
	public static void downloadImg(String imgUrl, String folderPath,String rename) {
		try {
			// 创建流
			BufferedInputStream in = new BufferedInputStream(new URL(imgUrl).openStream());
			// 生成图片名
			int index = imgUrl.lastIndexOf("/");
			String sName = imgUrl.substring(index + 1, imgUrl.length());
			if(rename!=null){
				//sName=rename+sName.substring(sName.indexOf("."),sName.length());
				sName = rename;
			}
			// 存放地址
			File folder = new File(folderPath);
			if(!folder.exists()){
				folder.mkdirs();
			}
			File img = new File(folderPath + sName);
			// 生成图片
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(img));
			byte[] buf = new byte[2048];
			int length = in.read(buf);
			while (length != -1) {
				out.write(buf, 0, length);
				length = in.read(buf);
			}
			in.close();
			out.close();
			logger.info("download["+img.getPath()+"]");
		} catch (Exception e) {
			logger.error("download error["+imgUrl+"]",e);
		}
	}
}
